<template>
  <el-container>
    <el-main>
      <div class="query-header">
        <el-form :model="form" :inline="true">
          <el-row justify="space-between">
            <el-form-item label="商品ID" class="form-label">
              <el-input v-model="form.id"></el-input>
            </el-form-item>
            <el-form-item label="商品名称" class="form-label">
              <el-input v-model="form.name"></el-input>
            </el-form-item>


            <el-form-item label="类型" class="form-label">
              <el-select v-model="form.type" placeholder="选择类型">
                <el-option
                    v-for="item in typeOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="产地" class="form-label">
              <el-input v-model="form.origin"></el-input>
            </el-form-item>
            <el-form-item label="制造商" class="form-label">
              <el-input v-model="form.manufacturer"></el-input>
            </el-form-item>
          </el-row>
          <el-row justify="space-between">
            <el-form-item class="form-label">
              <el-button type="primary" @click="queryAll">查询</el-button>
              <el-button @click="resetFilter">重置</el-button>
              <el-button @click="addFormVisible = true">新增</el-button>
              <el-button @click="getStatistics">统计信息</el-button>
              <el-button v-print="'#printTable'">打印</el-button>
              <el-button type="primary" @click="addTypeFormVisible = true" v-if="this.currentUser.group === 4">
                新增分类
              </el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <div class="query-content">
        <el-table :data="goods" style="width: 100%" stripe id="printTable">
          <el-table-column
              fixed
              prop="id"
              label="ID">
          </el-table-column>
          <el-table-column
              prop="name"
              label="名字">
          </el-table-column>
          <el-table-column
              prop="type"
              label="类别">
          </el-table-column>
          <el-table-column
              prop="origin"
              label="产地">
          </el-table-column>
          <el-table-column
              prop="price"
              label="价格">
          </el-table-column>
          <el-table-column
              prop="production"
              label="生产日期">
          </el-table-column>
          <el-table-column
              prop="manufacturer"
              label="制造商">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="160">
            <template #default="scope">
              <el-button @click="handleClick(scope.$index)" type="text" size="small">编辑</el-button>
              <el-button type="text" size="small" @click="handleDeleteClick(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
      <el-dialog title="新增分类" v-model="addTypeFormVisible">
        <el-form :model="addTypeForm">
          <el-form-item label="类型名" :label-width="formLabelWidth">
            <el-input v-model="addTypeForm.name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>

        <template #footer>

      <span class="dialog-footer">
       <el-button @click="addTypeFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="addType()">确 定</el-button>
      </span>
        </template>
      </el-dialog>
      <el-dialog title="新增商品" v-model="addFormVisible">
        <el-form :model="currentAdd" :inline="true">
          <el-form-item label="商品名" :label-width="formLabelWidth">
            <el-input v-model="currentAdd.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品类型" :label-width="formLabelWidth">
            <el-select v-model="currentAdd.type" placeholder="选择类型">
              <el-option
                  v-for="item in typeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
<!--            <el-input v-model="currentAdd.type" autocomplete="off"></el-input>-->
          </el-form-item>
          <el-form-item label="产地" :label-width="formLabelWidth">
            <el-input v-model="currentAdd.origin" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" :label-width="formLabelWidth">
            <el-input v-model="currentAdd.price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="生产日期" :label-width="formLabelWidth">
            <el-date-picker
                v-model="currentAdd.production"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
                value-format="YYYY-MM-DD"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="制造商" :label-width="formLabelWidth">
            <el-input v-model="currentAdd.manufacturer" autocomplete="off"></el-input>
          </el-form-item>

        </el-form>
        <template #footer>
      <span class="dialog-footer">
       <el-button @click="addFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="addNewGood()">确 定</el-button>
      </span>
        </template>
      </el-dialog>
      <el-dialog title="编辑商品" v-model="editFormVisible">
        <el-form :model="currentEdit" :inline="true">
          <el-form-item label="商品ID" :label-width="formLabelWidth">
            <el-input v-model="currentEdit.id" autocomplete="off" disabled=""></el-input>
          </el-form-item>
          <el-form-item label="商品名" :label-width="formLabelWidth">
            <el-input v-model="currentEdit.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品类型" :label-width="formLabelWidth">
            <el-select v-model="currentEdit.type" placeholder="选择类型">
              <el-option
                  v-for="item in typeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
<!--            <el-input v-model="currentEdit.type" autocomplete="off"></el-input>-->
          </el-form-item>
          <el-form-item label="产地" :label-width="formLabelWidth">
            <el-input v-model="currentEdit.origin" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" :label-width="formLabelWidth">
            <el-input v-model="currentEdit.price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="生产日期" :label-width="formLabelWidth">
            <el-date-picker
                v-model="currentEdit.production"
                type="date"
                :disabled-date="disabledDate"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="制造商" :label-width="formLabelWidth">
            <el-input v-model="currentEdit.manufacturer" autocomplete="off"></el-input>
          </el-form-item>

        </el-form>
        <template #footer>
      <span class="dialog-footer">
       <el-button @click="editFormVisible = false">取 消</el-button>
       <el-button type="primary" @click="saveEdit()">确 定</el-button>
      </span>
        </template>
      </el-dialog>
      <el-dialog v-model="statisticsVisible" title="商品统计">
        <highcharts :options="chartOptions"></highcharts>
      </el-dialog>
    </el-main>
  </el-container>

</template>

<style scoped>
.query-header {
  background-color: rgba(135, 206, 250, 0.3);
  border-radius: 5px;
  padding: 5px;
}

.form-label {
  font-weight: bold;
  margin-top: 18px;
}
</style>
<script>
import {postBackend} from "@/main";
import {ElNotification} from "element-plus";
import qs from "qs";
import print from 'vue3-print-nb'


export default {
  directives: {
    print
  },
  name: "GoodsManagePage",
  data() {
    return {
      printObj: {
        id: "printTable",
        popTitle: '商品管理',
        extraCss: "",
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>',
      },
      chartOptions: {},
      typeOptions: [
        ""
      ],
      currentUser: {},
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      editFormVisible: false,
      addFormVisible: false,
      statisticsVisible: false,
      addTypeFormVisible: false,
      formLabelWidth: "140px",
      addTypeForm: {
        name: ''
      },
      form: {
        id: '',
        name: '',
        type: '',
        origin: '',
        manufacturer: '',
      },
      currentAdd: {
        name: '',
        type: '',
        origin: '',
        price: '',
        production: '',
        manufacturer: '',
      },
      currentEdit: {
        id: '',
        name: '',
        type: '',
        origin: '',
        price: '',
        production: '',
        manufacturer: '',
      },
      goods: [],
      pageSize: 20,
      currentPage: 1,
      total: 0,
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.queryMe()
      this.queryTypes()
    })
  },
  methods: {
    printPage(){
      this.$nextTick(() => {
        print
        this.$refs.printTable.print()
      });
    },
    getStatistics() {
      this.statisticsVisible = true
      postBackend("/api/goods/statistics", {}, res => {
        if (res.data.code !== 0) {
          return
        }
        const counts = res.data.entity
        let sum = 0
        for (const key in counts) {
          const value = counts[key]
          sum += value
        }
        const chartData = []
        for (const key in counts) {
          const value = counts[key]
          const percent = value / sum * 100.0
          chartData.push([key, parseFloat(percent.toFixed(2))])
        }
        this.chartOptions = {
          title: {
            text: '商品分类占比',
            align: 'center',
            verticalAlign: 'middle',
            y: 60
          },
          tooltip: {
            headerFormat: '{series.name}<br>',
            pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
          },
          plotOptions: {
            pie: {
              dataLabels: {
                enabled: true,
                distance: -50,
                style: {
                  fontWeight: 'bold',
                  color: 'white',
                  textShadow: '0px 1px 2px black'
                }
              },
              startAngle: -90, // 圆环的开始角度
              endAngle: 90,    // 圆环的结束角度
              center: ['50%', '75%']
            }
          },
          series: [{
            type: 'pie',
            name: '商品分类占比',
            innerSize: '50%',
            data: chartData
          }]
        }
      }, err => {
        console.log(err)
      })

    },
    addType() {
      this.addTypeFormVisible = false
      postBackend("/api/category/add", this.addTypeForm, res => {
        console.log(res.data)
        if (res.data.code === 0) {
          ElNotification({
            title: '成功',
            message: '成功添加'
          })
          this.queryTypes()
        } else {
          ElNotification({
            title: '失败',
            message: '更新失败，原因: ' + res.data.msg,
            type: 'warning'
          })
        }
      }, err => {
        ElNotification({
          title: '失败',
          message: '更新失败，原因: ' + err,
          type: 'warning'
        })
        console.log(err);
      })
    },
    queryMe() {
      postBackend("/api/user/info", {}, res => {
        if (res.data.code === 1) {
          return
        }
        this.currentUser = res.data.entity
      }, err => {
        console.log(err)
      })
    },
    resetFilter() {
      this.form = {
        id: '',
        name: '',
        type: '',
        origin: '',
        manufacturer: ''
      }
    },
    queryTypes() {
      postBackend('/api/category/list', {}, res => {
        console.log(res.data)
        this.typeOptions = [""]
        if (res.data.code === 0) {
          for (const entityKey in res.data.entity) {
            this.typeOptions.push(res.data.entity[entityKey]["name"])
          }
        } else {
          ElNotification({
            title: '失败',
            message: '类型查询失败' + res.data.msg,
            type: 'warning'
          })
        }

      }, err => {
        ElNotification({
          title: '失败',
          message: '类型查询失败，原因: ' + err,
          type: 'warning'
        })
        console.log(err);
      })
    },
    disabledDate(time) {
      return time.getTime() > Date.now();
    },
    handleDeleteClick(row) {
      const id = this.goods[row].id
      this.deleteGood(id)
    },
    deleteGood(goodId) {
      this.addFormVisible = false
      postBackend('/api/goods/delete', {id: goodId}, res => {
        console.log(res.data)
        if (res.data.code === 0) {
          ElNotification({
            title: '成功',
            message: '删除成功'
          })
          this.queryAll()
        } else {
          ElNotification({
            title: '失败',
            message: '更新失败，原因: ' + res.data.msg,
            type: 'warning'
          })
        }
      }, err => {
        ElNotification({
          title: '失败',
          message: '更新失败，原因: ' + err,
          type: 'warning'
        })
        console.log(err);
      })
    },
    addNewGood() {
      this.addFormVisible = false
      postBackend('/api/goods/add', this.currentAdd, res => {
        console.log(res.data)
        if (res.data.code === 0) {
          ElNotification({
            title: '成功',
            message: '成功添加'
          })
          this.queryAll()
        } else {
          ElNotification({
            title: '失败',
            message: '更新失败，原因: ' + res.data.msg,
            type: 'warning'
          })
        }
      }, err => {
        ElNotification({
          title: '失败',
          message: '更新失败，原因: ' + err,
          type: 'warning'
        })
        console.log(err);
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.queryAll()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryAll()
    },
    saveEdit() {
      postBackend('/api/goods/update', this.currentEdit, res => {
            console.log(res.data)
            if (res.data.code === 0) {
              ElNotification({
                title: '成功',
                message: '更新成功'
              })
            } else {
              ElNotification({
                title: '失败',
                message: '更新失败，原因: ' + res.data.msg,
                type: 'warning'
              })
            }
          },
          err => {
            ElNotification({
              title: '失败',
              message: '更新失败，原因: ' + err,
              type: 'warning'
            })
            console.log(err);
          }
      )
      this.editFormVisible = false
    },
    handleClick(row) {
      this.currentEdit = this.goods[row]
      this.editFormVisible = true
    },
    queryAll() {
      const goodFilter = this.form
      if (goodFilter.id === "") {
        goodFilter.id = -1
      }
      console.log(qs.stringify({
        span: this.pageSize,
        start: this.pageSize * (this.currentPage - 1),
        filter: goodFilter
      }));
      postBackend('/api/goods/show', {
        span: this.pageSize,
        start: this.pageSize * (this.currentPage - 1),
        filter: goodFilter
      }, res => {
        console.log(res)
        if (res.data.code === 1) {
          localStorage.clear()
          location.reload()
          return
        }
        this.goods = res.data.entity.data;
        this.total = res.data.entity.count
        console.log(this.goods)
      }, err => {
        console.log(err);
      })
    }
  }
}
</script>

